<script lang="tsx">
import { defineComponent, ref, watch } from 'vue';
import { $t } from '@vben/locales';
import BaseDrawer from '#/components/common/base-drawer.vue';
import { obsDownload } from '#/utils/obs';
import EmptyImage from "#/assets/images/banner-empty.png"
import PlayVideo from './play-video.vue';
import dayjs from 'dayjs';

export default defineComponent({
  name: 'RegistrationAudit',
  props: {
    modelValue: {
      type: Boolean,
      default: false,
    },
    data: {
      type: Object,
      default: () => ({}),
    },
    submitLoading: {
      type: Boolean,
      default: false,
    },
    registrationStatusMap: {
      type: Object,
      default: () => ({}),
    },
    worksStatusMap: {
      type: Object,
      default: () => ({}),
    },
  },
  emits: ['update:modelValue', 'update:registrationStatus', 'update:worksStatus', 'cancel'],
  setup(props, { emit }) {
    const formRef = ref();
    const visible = ref(false);
    const rejectReason = ref({
      registrationReason: '',
      worksReason: '',
    });
    const initFormData = () => {
      return {
        worksName: '', // 作品名称
        trackName: '', // 赛道
        organizationName: '', // 所属单位
        teamName: '', // 团队名称
        worksPatent: '', // 专利文件
        worksCopyright: '', // 著作权文件
        companyAuthCertificate: '', // 授权证明
        accessChannel: undefined, // 了解渠道
        receivablesAccount: undefined, // 收款账号
        accountName: undefined, // 账号名
        bankDeposit: '', // 开户行
        worksIntro: '', // 作品简介
        videoAssetId: '', // 作品介绍视频
        worksIntroduceFile: '' // 作品讲解课件
      }
    }

    // 表单数据
    const localFormData = ref(initFormData() as Record<string, any>);
    // 基本信息表单配置
    const basicFormColumns = ref([
      {
        prop: 'worksName',
        label: $t('competition.registrationInfo.compName'),
        render: () => {
          return (
            <div>
              <div class="text-[16px] text-[#191919]">{localFormData.value.worksName || '--'}</div>
            </div>
          );
        }
      },
      {
        prop: 'trackName',
        label: $t('competition.registrationInfo.trackName'),
        render: () => {
          return (
            <div>
              <div class="text-[16px] text-[#191919]">{localFormData.value.trackName || '--'}</div>
            </div>
          );
        }
      },
      {
        prop: 'organizationName',
        label: $t('competition.organizationName'),
        render: () => {
          return (
            <div>
              <div class="text-[16px] text-[#191919]">{localFormData.value.organizationName || '--'}</div>
            </div>
          );
        }
      },
      {
        prop: 'teamName',
        label: $t('competition.teamName'),
        render: () => {
          return (
            <div>
              <div class="text-[16px] text-[#191919]">{localFormData.value.teamName || '--'}</div>
            </div>
          );
        }
      },
      {
        prop: 'worksPatent',
        label: $t('competition.registrationInfo.worksPatent'),
        render: () => {
          return (
            <div>
              <div class="w-full break-all overflow-hidden text-ellipsis cursor-pointer whitespace-nowrap hover:text-primary text-[16px] text-[#191919]">
                {!!localFormData.value.worksPatent && (
                  <span onClick={() => handlerDownload(localFormData.value.worksPatent)}>{localFormData.value.worksPatent}</span>
                )}
                {!localFormData.value.worksPatent && (
                  <span>{'--'}</span>
                )}
              </div>
            </div>
          );
        }
      },
      {
        prop: 'worksCopyright',
        label: $t('competition.registrationInfo.worksCopyright'),
        render: () => {
          return (
            <div>
              <div class="w-full break-all overflow-hidden text-ellipsis cursor-pointer whitespace-nowrap hover:text-primary text-[16px] text-[#191919]">
                {!!localFormData.value.worksCopyright && (
                  <span onClick={() => handlerDownload(localFormData.value.worksCopyright)}>{localFormData.value.worksCopyright}</span>
                )}
                {!localFormData.value.worksCopyright && (
                  <span>{'--'}</span>
                )}
              </div>
            </div>
          );
        }
      },
      {
        prop: 'companyAuthCertificate',
        label: $t('competition.registrationInfo.companyAuthCertificate'),
        render: () => {
          return (
            <div>
              <div class="w-full break-all overflow-hidden text-ellipsis cursor-pointer whitespace-nowrap hover:text-primary text-[16px] text-[#191919]">
                {!!localFormData.value.companyAuthCertificate && (
                  <span onClick={() => handlerDownload(localFormData.value.companyAuthCertificate)}>{localFormData.value.companyAuthCertificate}</span>
                )}
                {!localFormData.value.companyAuthCertificate && (
                  <span>{'--'}</span>
                )}
              </div>
            </div>
          );
        }
      },
      {
        prop: 'accessChannel',
        label: $t('competition.registrationInfo.accessChannel'),
        render: () => {
          return (
            <div>
              <div class="text-[16px] text-[#191919]">{localFormData.value.accessChannel || '--'}</div>
            </div>
          );
        }
      },
      {
        prop: 'receivablesAccount',
        label: $t('competition.registrationInfo.receivablesAccount'),
        render: () => {
          return (
            <div>
              <div class="text-[16px] text-[#191919]">{localFormData.value.receivablesAccount || '--'}</div>
            </div>
          );
        }
      },
      {
        prop: 'accountName',
        label: $t('competition.registrationInfo.accountName'),
        render: () => {
          return (
            <div>
              <div class="text-[16px] text-[#191919]">{localFormData.value.accountName || '--'}</div>
            </div>
          );
        }
      },
      {
        prop: 'bankDeposit',
        label: $t('competition.registrationInfo.bankDeposit'),
        render: () => {
          return (
            <div>
              <div class="text-[16px] text-[#191919]">{localFormData.value.bankDeposit || '--'}</div>
            </div>
          );
        }
      },
      {
        prop: 'worksIntro',
        label: $t('competition.registrationInfo.worksIntro'),
        formItemProps: {
          style: {
            width: '100%',
            margin: '0 0 20px 0',
          },
        },
        render: () => {
          return (
            <div>
              <div class="text-[16px] text-[#191919]">{localFormData.value.worksIntro || '--'}</div>
            </div>
          );
        }
      },
      {
        prop: 'videoAssetId',
        label: $t('competition.registrationInfo.videoAssetId'),
        render: () => {
          return (
            <div>
              {!!localFormData.value.videoAssetId && (
                <div class="w-[300px] h-[250px] text-[#191919] rounded-[4px] border border-[#DCDFE6]">
                  <PlayVideo src={localFormData.value.videoAssetId} style={{ width: '100%', height: '100%' }} />
                </div>
              )}
              {!localFormData.value.videoAssetId && (
                <div class="w-[300px] h-[250px] text-[#595959] flex items-center justify-center rounded-[4px] border border-[#DCDFE6]">
                  <el-empty imageSize={100} image={EmptyImage} class="text-[#595959]"
                    description={$t('certificate.settingBanner.uploadBanner')} />
                </div>
              )}
            </div>
          );
        }
      },
      {
        prop: 'worksIntroduceFile',
        label: $t('competition.registrationInfo.worksIntroduceFile'),
        render: () => {
          return (
            <div>
              <div class="w-full break-all overflow-hidden text-ellipsis cursor-pointer whitespace-nowrap hover:text-primary text-[16px] text-[#191919]">
                {!!localFormData.value.worksIntroduceFile && (
                  <span onClick={() => handlerDownload(localFormData.value.worksIntroduceFile)}>{localFormData.value.worksIntroduceFile}</span>
                )}
                {!localFormData.value.worksIntroduceFile && (
                  <span class="text-[#595959]">课件未上传</span>
                )}
              </div>
            </div>
          );
        }
      }
    ]);

    // 表单验证规则
    const formRules = {

    };

    // 监听 modelValue 变化
    watch(() => props.modelValue, async (val) => {
      visible.value = val;
      if (val) {
        rejectReason.value = {
          registrationReason: props.data.registrationReviewOpinion || '',
          worksReason: props.data.worksReviewOpinion || '',
        };
        localFormData.value = props.data;
      } else {
        initForm();
        rejectReason.value = {
          registrationReason: '',
          worksReason: '',
        };
      }
    }, { deep: true });



    const handlerDownload = async (fileName: string) => {
      obsDownload({
        Key: fileName,
      }, (err: any, result: any) => {
        if (err) {
          console.error('获取失败:', err);
          return;
        }
        const blob = new Blob([result.InterfaceResult.Content]);

        // 创建Blob对象并触发下载
        const url = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = fileName; // 可自定义下载文件名
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        URL.revokeObjectURL(url); // 清理内存
      })
    }

    // 处理关闭
    const handleClose = () => {
      initForm();
      emit('update:modelValue', false);
      emit('cancel');
    };

    // 更新表单数据
    const handleFormUpdate = (data: any) => {
      localFormData.value = data;
    };

    // 初始化表单数据
    const initForm = () => {
      localFormData.value = initFormData();
    }

    const handleRegistStatus = (status: number) => {
      const params = {
        id: props.data.id,
        reviewStatus: status,
        reviewOpinion: rejectReason.value.registrationReason
      }
      console.log('params', params);
      emit('update:registrationStatus', params);
    }

    const handleWorksStatus = (status: number) => {
      const params = {
        id: props.data.id,
        reviewStatus: status,
        reviewOpinion: rejectReason.value.worksReason
      }
      console.log('params', params);
      emit('update:worksStatus', params);
    }

    return () => (
      <BaseDrawer
        modelValue={visible.value}
        title={$t('competition.registrationInfo.worksDetail')}
        onUpdate:modelValue={(val: boolean) => emit('update:modelValue', val)}
        onClose={handleClose}
        showFooter={true}
        cancelText={$t('common.cancelTxt')}
        v-slots={{
          footer: () => (
            <div class="flex justify-end">
              <el-button onClick={handleClose}>{$t('common.cancelTxt')}</el-button>
              <el-button disabled={props.submitLoading || props.data.registrationStatus === 3} plain type="danger" onClick={() => handleRegistStatus(3)}>{$t('competition.registrationInfo.registrationRejectBtn')}</el-button>
              <el-button disabled={props.submitLoading || props.data.registrationStatus === 2} plain type="primary" onClick={() => handleRegistStatus(2)}>{$t('competition.registrationInfo.registrationPassBtn')}</el-button>
              {
                props.data.registrationStatus > 1 && (
                  <>
                    <el-button disabled={props.submitLoading || props.data.worksStatus === 3} type="danger" onClick={() => handleWorksStatus(3)}>{$t('competition.registrationInfo.worksRejectBtn')}</el-button>
                    <el-button disabled={props.submitLoading || props.data.worksStatus === 2} type="primary" onClick={() => handleWorksStatus(2)}>{$t('competition.registrationInfo.worksPassBtn')}</el-button>
                  </>
                )
              }
            </div>
          )
        }}
      >
        <div class="add-registration-info-container">
          <div class="form-section">
            <div class="section-content">
              <base-form
                ref={formRef}
                columns={basicFormColumns.value}
                modelValue={localFormData.value}
                rules={formRules}
                label-position="right"
                label-width="110px"
                inline={true}
                onUpdate:modelValue={handleFormUpdate}
              />
            </div>
            <div class="section-content">
              <div class="text-[16px] text-[#191919] text-500 mb-[8px] title">{$t('competition.registrationInfo.registrationAuditOpinion')}</div>
              <div class="text-[16px] text-[#191919] content mb-[8px]">
                <el-input maxlength={200} rows={1} show-word-limit v-model={rejectReason.value.registrationReason} type="textarea" />
              </div>
              {
                props.data.registrationStatus > 1 && (
                  <div class="flex justify-start items-center text-[14px] leading-[22px]">
                    <span class="text-[#191919]">{props.data.registrationReviewPeople || '--'}</span>
                    <span class="text-[#E5484D] ml-3 mr-3">{props.registrationStatusMap[props.data.registrationStatus] || '--'}</span>
                    <span class="text-[#191919]">{props.data.registrationReviewTime ? dayjs(props.data.registrationReviewTime).format('YYYY-MM-DD HH:mm:ss') : '--'}</span>
                  </div>
                )}
              {props.data.registrationStatus > 1 && (
                <div class="mt-[20px]">
                  <div class="text-[16px] text-[#191919] text-500 mb-[8px] title">{$t('competition.registrationInfo.worksAuditOpinion')}</div>
                  <div class="text-[16px] text-[#191919] content">
                    <el-input maxlength={200} rows={1} show-word-limit v-model={rejectReason.value.worksReason} type="textarea" />
                  </div>
                  <div class="flex justify-start items-center text-[14px] leading-[22px]">
                    <span class="text-[#191919]">{props.data.worksReviewPeople || '--'}</span>
                    <span class="text-[#E5484D] ml-3 mr-3">{props.worksStatusMap[props.data.worksStatus] || '--'}</span>
                    <span class="text-[#191919]">{props.data.worksReviewTime ? dayjs(props.data.worksReviewTime).format('YYYY-MM-DD HH:mm:ss') : '--'}</span>
                  </div>
                </div>
              )}
            </div>
          </div>
        </div>
      </BaseDrawer>
    );
  }
});
</script>

<style lang="scss" scoped>
.add-registration-info-container {
  .form-section {
    .section-content {
      :deep(.base-form-item) {
        margin-bottom: 20px;

        .el-form-item__content {
          width: 100%;
        }
      }

      // 设置宽度不为100%且排列在右边的表单项，margin-right为0
      :deep(.el-form-item:not([style*="width: 100%"])) {
        width: calc((100% - 32px)/2);

        &:nth-of-type(even) {
          margin-right: 0 !important;
        }
      }

      :deep(.el-form--inline .el-form-item) {
        vertical-align: top;
      }
    }
  }
}
</style>
